package com.sgb.kjwl.view.ui.fragment.self;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.swgk.core.event.MessageEvent;
import com.sgb.kjwl.databinding.FragmentShoppingCartBinding;
import com.sgb.kjwl.di.shopping.DaggerShoppingFragComponent;
import com.sgb.kjwl.di.shopping.ShoppingFragModule;
import com.sgb.kjwl.model.entity.shopping.ShoppingCarResponse;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.StatementActivity;
import com.sgb.kjwl.view.ui.adapter.shopping.ShopParentAdapter;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.shopping.ShoppingCarModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 采购单
 *
 * @author Administrator
 */
public class ShoppingCartFragment extends AppFragment {
    FragmentShoppingCartBinding binding;
    @Inject
    ShoppingCarModel viewModel;
    private final List<ShoppingCarResponse> mShoppingCarEntities = new ArrayList<>();

    private ShopParentAdapter mAdapterParent;
    private final List<ShoppingCarResponse> checkData = new ArrayList<>();
    private final List<String> delIds = new ArrayList<>();
    private boolean mIsSelectAll;
    private double mTotalPrices;
    private boolean isOnResumed = false;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            View decor = requireActivity().getWindow().getDecorView();
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_shopping_cart, container, false);
        binding.setViewModel(viewModel);
        View decor = requireActivity().getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

        binding.actionBarImageLeft.setOnClickListener(view -> requireActivity().finish());
        binding.btnOrder.setOnClickListener(v -> {
            getCheckItem();
            if (checkData.size() > 0) {
                verificationSuccess();
            } else {
                MToast.showToast(getActivity(), "请选择结算商品");
            }
        });
        TextView noData = binding.emptyView.blankView.findViewById(R.id.no_data_tv);
        noData.setText("您的采购单还是空的，快去选购商品吧!");
        binding.tvTitlebarRight.setOnClickListener(view -> {
            String edit = binding.tvTitlebarRight.getText().toString().trim();
            binding.tvTitlebarRight.setText(edit.contains("管理") ? "完成" : "管理");
            binding.rlTotalPrice.setVisibility(edit.contains("管理") ? View.GONE : View.VISIBLE);
            binding.btnOrder.setVisibility(edit.contains("管理") ? View.GONE : View.VISIBLE);
            binding.btnDelete.setVisibility(edit.contains("管理") ? View.VISIBLE : View.GONE);
            binding.btnDelInvalid.setVisibility(edit.contains("管理") ? View.VISIBLE : View.GONE);
        });

        binding.llSelectAll.setOnClickListener(v -> {
            mIsSelectAll = !mIsSelectAll;
            mTotalPrices = 0;
            for (ShoppingCarResponse carEntity : mAdapterParent.getData()) {
                carEntity.setChecked(mIsSelectAll);
                for (ShoppingCarResponse.ItemsData dataBean : carEntity.getItems()) {
                    if (dataBean.getItemStatus() == 1) {
                        mTotalPrices = mTotalPrices + dataBean.getPrice() * dataBean.getItemNum();
                    }
                }
            }
            mAdapterParent.notifyDataSetChanged();
            binding.tvTotalPrice.setText("¥" + (mTotalPrices != 0 ? UiUtil.getDecimalFormat(mTotalPrices) : "0"));
            binding.ivSelectAll.setImageResource(mIsSelectAll ? R.drawable.icon_select_item : R.drawable.icon_no_select_item);
            if (!mIsSelectAll) {
                mTotalPrices = 0;
                binding.tvTotalPrice.setText("¥0");
            }
            setOrderButtonEnable(mTotalPrices != 0);
        });

        binding.btnDelete.setOnClickListener(v -> {
            delIds.clear();
            for (ShoppingCarResponse carEntity : mAdapterParent.getData()) {
                for (ShoppingCarResponse.ItemsData dataBean : carEntity.getItems()) {
                    if (dataBean.isChecked()) {
                        delIds.add(String.valueOf(dataBean.getId()));
                    }
                }
            }
            if (delIds.size() > 0) {
                showDeleteDialog(delIds, false);
            } else {
                MToast.showToast(getActivity(), "请选择要删除的商品");
            }
        });

        binding.btnDelInvalid.setOnClickListener(view -> {
            delIds.clear();
            for (ShoppingCarResponse carEntity : mAdapterParent.getData()) {
                for (ShoppingCarResponse.ItemsData dataBean : carEntity.getItems()) {
                    if (dataBean.getItemStatus() != 1) {
                        delIds.add(String.valueOf(dataBean.getId()));
                    }
                }
            }
            if (delIds.size() > 0) {
                showDeleteDialog(delIds, true);
            } else {
                MToast.showToast(getActivity(), "没有失效商品");
            }
        });
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initExpandableListView();
        viewModel.getShoppingCarInfo(false);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerShoppingFragComponent.builder().appComponent(appComponent).shoppingFragModule(new ShoppingFragModule(this)).build().inject(this);
    }

    /**
     * 初始化ExpandableListView
     * 创建数据适配器adapter，并进行初始化操作
     */
    private void initExpandableListView() {
        mAdapterParent = new ShopParentAdapter(getActivity(), mShoppingCarEntities);
        binding.elvShoppingCar.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
        binding.elvShoppingCar.setAdapter(mAdapterParent);
    }

    /**
     * 初始化ExpandableListView的数据
     * 并在数据刷新时，页面保持当前位置
     *
     * @param data 购物车的数据
     */
    private void initExpandableListViewData(List<ShoppingCarResponse> data) {
        if (data != null && data.size() > 0) {
            mShoppingCarEntities.clear();
            mShoppingCarEntities.addAll(data);
            mAdapterParent.setNewData(data);
            binding.tvTitlebarRight.setVisibility(View.VISIBLE);
            binding.tvTitlebarRight.setText("管理");
            binding.emptyView.blankView.setVisibility(View.GONE);
            binding.elvShoppingCar.setVisibility(View.VISIBLE);
            binding.rl.setVisibility(View.VISIBLE);
            binding.rlTotalPrice.setVisibility(View.VISIBLE);
            binding.btnOrder.setVisibility(View.VISIBLE);
            binding.btnDelete.setVisibility(View.GONE);
            binding.btnDelInvalid.setVisibility(View.GONE);
        } else {
            binding.tvTitlebarRight.setVisibility(View.GONE);
            binding.emptyView.blankView.setVisibility(View.VISIBLE);
            binding.elvShoppingCar.setVisibility(View.GONE);
            binding.rl.setVisibility(View.GONE);
        }
    }

    /**
     * 展示删除的dialog
     */
    private void showDeleteDialog(final List<String> deleteIds, boolean isInvalidation) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(true);
        TextView tvMessage = view.findViewById(R.id.tv_message);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        TextView tvLogoutConfirm = view.findViewById(R.id.tv_logout_confirm);
        tvLogoutConfirm.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        TextView tvLogoutCancel = view.findViewById(R.id.tv_logout_cancel);
        tvLogoutCancel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tvTitle.setVisibility(View.GONE);
        if (!isInvalidation) {
            tvMessage.setText("确认删除该商品吗？");
        } else {
            tvMessage.setText("确认删除全部失效商品吗？");
        }
        tvMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tvLogoutCancel.setOnClickListener(v -> roundCornerDialog.dismiss());
        tvLogoutConfirm.setOnClickListener(v -> {
            if (!isInvalidation) {
                viewModel.deleteShoppingCar(deleteIds);
            } else {
                viewModel.deleteInvalidationShoppingCar();
            }
            roundCornerDialog.dismiss();
        });
    }

    /***
     * 获取数据
     */
    public void showShoppingCarDetail(List<ShoppingCarResponse> data) {
        mIsSelectAll = false;
        binding.ivSelectAll.setImageResource(R.drawable.icon_no_select_item);
        initExpandableListViewData(data);
        refreshTotalPrices();
    }

    public void setCheckResult(boolean result) {
        if (result) {
            MToast.showToast(getContext(), "功能开发中...");
        } else {
            MToast.showToast(getContext(), "商品清单中存在价格不正确情况");
            viewModel.getShoppingCarInfo(false);
        }
    }

    private void getCheckItem() {
        checkData.clear();
        if (mAdapterParent.getData().size() > 0) {
            for (ShoppingCarResponse carEntity : mAdapterParent.getData()) {
                ShoppingCarResponse shoppingCarResponse = new ShoppingCarResponse();
                if (carEntity.getItems() != null && carEntity.getItems().size() != 0) {
                    List<ShoppingCarResponse.ItemsData> itemsData = new ArrayList<>();
                    boolean isAdd = false;
                    for (ShoppingCarResponse.ItemsData dataBean : carEntity.getItems()) {
                        if (dataBean != null && dataBean.isChecked() && dataBean.getItemStatus() == 1) {
                            isAdd = true;
                            itemsData.add(dataBean);
                        }
                    }
                    if (isAdd) {
                        shoppingCarResponse.setItems(itemsData);
                    }
                }
                if (shoppingCarResponse.getItems() != null && shoppingCarResponse.getItems().size() != 0) {
                    shoppingCarResponse.setCompanyId(carEntity.getCompanyId());
                    shoppingCarResponse.setCompanyName(carEntity.getCompanyName());
                    shoppingCarResponse.setCompanyNo(carEntity.getCompanyNo());
                    shoppingCarResponse.setSelfSupportTag(carEntity.getSelfSupportTag());
                    shoppingCarResponse.setImAccount(carEntity.getImAccount());
                    shoppingCarResponse.setPayState(carEntity.getPayState());
                    shoppingCarResponse.setIsOpenAccount(carEntity.getIsOpenAccount());
                    checkData.add(shoppingCarResponse);
                }
            }
        }
    }

    /***
     * 获取新数据，局部刷新
     */
    public void notifyData(List<ShoppingCarResponse> list) {
        mShoppingCarEntities.clear();
        if (list != null && list.size() > 0) {
            mShoppingCarEntities.addAll(list);
            mAdapterParent.setNewData(list);
            UiUtil.sendMsg(EventConstant.EVENT_SHOP_DELETE, "" + mShoppingCarEntities.size());
            mAdapterParent.notifyDataSetChanged();
        } else {
            UiUtil.sendMsg(EventConstant.EVENT_SHOP_DELETE, "" + 0);
            binding.tvTitlebarRight.setVisibility(View.GONE);
            binding.emptyView.blankView.setVisibility(View.VISIBLE);
            binding.elvShoppingCar.setVisibility(View.GONE);
            binding.rl.setVisibility(View.GONE);
        }
        refreshTotalPrices();
    }

    @Subscribe
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant
                    .EVENT_HIDE_KEYBOARD:
                KeyboardUtils.hideSoftInput(requireActivity());
                break;
            case EventConstant
                    .EVENT_UPDATE_PRICES:
                if (event.data instanceof ShoppingCarResponse.ItemsData) {
                    ShoppingCarResponse.ItemsData data = (ShoppingCarResponse.ItemsData) event.data;
                    viewModel.updateShoppingCar(String.valueOf(data.getId()), String.valueOf(data.getItemNum()));
                    refreshTotalPrices();
                }
                break;
            case EventConstant.EVENT_ITEM_SELSECT:
                if (isAllChecked()) {
                    binding.ivSelectAll.setImageResource(R.drawable.icon_select_item);
                    mIsSelectAll = true;
                } else {
                    binding.ivSelectAll.setImageResource(R.drawable.icon_no_select_item);
                    mIsSelectAll = false;
                }
                refreshTotalPrices();
                break;
            default:
                break;
        }
    }

    private boolean isAllChecked() {
        List<ShoppingCarResponse> adapterParentData = mAdapterParent.getData();
        if (adapterParentData != null && adapterParentData.size() != 0) {
            for (ShoppingCarResponse dataBean : adapterParentData) {
                if (!dataBean.isChecked()) {
                    return false;
                } else {
                    for (ShoppingCarResponse.ItemsData itemsData : dataBean.getItems()) {
                        if (!itemsData.isChecked()) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    @SuppressLint("SetTextI18n")
    private void refreshTotalPrices() {
        mTotalPrices = 0;
        if (mAdapterParent.getData().size() > 0) {
            for (ShoppingCarResponse carEntity : mAdapterParent.getData()) {
                for (ShoppingCarResponse.ItemsData dataBean : carEntity.getItems()) {
                    if (dataBean.isChecked() && dataBean.getItemStatus() == 1) {
                        mTotalPrices = mTotalPrices + dataBean.getPrice() * dataBean.getItemNum();
                    }
                }
            }
        }
        binding.tvTotalPrice.setText("¥" + (mTotalPrices != 0 ? UiUtil.getDecimalFormat(mTotalPrices) : "0"));
        setOrderButtonEnable(mTotalPrices != 0);
    }

    private void setOrderButtonEnable(boolean isEnable) {
        binding.btnOrder.setEnabled(isEnable);
        if (isEnable) {
            binding.btnOrder.getBackground().setAlpha(255);
        } else {
            binding.btnOrder.getBackground().setAlpha(102);
        }
    }

    /***
     * 商品校验成功
     */
    public void verificationSuccess() {
        Intent intent = new Intent(getActivity(), StatementActivity.class);
        intent.putExtra("PURCHASE_ORDER", (Serializable) checkData);
        startActivity(intent);
    }

    /***
     * 商品校验失败
     */
    public void verificationFailure(String msg) {
        MToast.showToast(getActivity(), msg);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isOnResumed) {
            viewModel.getShoppingCarInfo(false);
        } else {
            isOnResumed = true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
